Golang : On enumeration
In Golang, it is fairly simple to declare enumeration. Just group the similar items into a const
group and use the iota
keyword.
For example, to declares constants :
const Monday = 1
const Tuesday = 2
Enumeration is formed by putting constants into parentheses. For example :
const (
Monday = 1
Tuesday = 2
Wednesday = 3
)
Golang has one keyword iota
that make the consts into enum.
const (
Monday = iota
Tuesday
Wednesday
)
and let say you want to explicit declare the constants type. You can do something like :
type Day int
const (
Monday Day = iota
Tuesday
Wednesday
)
and this code will test out the enumeration :
package main
import (
"fmt"
)
type Day int
const (
Monday Day = iota // starts from 0
Tuesday
Wednesday
Thursday
Friday
)
func main() {
fmt.Println(Monday) // should return 0
fmt.Println(Friday) // should print 4
}
Output :
0
4
add a variable and a method to print out the string value instead of iota.
// [...] is to tell the Go intrepreter/compiler to figure out the array size
var days = [...]string {"Monday","Tuesday","Wednesday","Thursday","Friday",}
func (day Day) String() string {
return days[day]
}
and the codes below will printout the enumeration in string.
package main
import (
"fmt"
)
type Day int
const (
Monday Day = iota // starts from 0
Tuesday
Wednesday
Thursday
Friday
)
// [...] is to tell the Go intrepreter/compiler to figure out the array size
var days = [...]string {"Monday","Tuesday","Wednesday","Thursday","Friday",}
func (day Day) String() string {
return days[day]
}
func main() {
fmt.Println(Monday) // should return Monday
fmt.Println(Friday) // should print Friday
}
Output :
Monday
Friday
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.7k Golang : Use NLP to get sentences for each paragraph example
+20.8k Golang : Sort and reverse sort a slice of strings
+10.6k PHP : Convert(cast) bigInt to string
+8.7k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+17.9k Golang : Get command line arguments
+13.5k Golang : Gin framework accept query string by post request example
+13.1k Golang : Generate Code128 barcode
+12.6k Golang : Convert IPv4 address to packed 32-bit binary format
+18.8k Golang : Populate dropdown with html/template example
+11.3k Golang : Concurrency and goroutine example
+31.1k Golang : How to convert(cast) string to IP address?
+14.1k Golang : How to filter a map's elements for faster lookup